from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.http import Http404
from jobs.models import Job,Cities,JobTypes
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from jobs.models import Resume
from jobs.forms import ResumeForm
from obs import ObsClient
from recruitment.settings import ACCESS_KEY_ID,SECRET_ACCESS_KEY,BUCKET_NAME,ENDPOINT

def joblist(requset):
    job_list = Job.objects.order_by('job_type')
    template = loader.get_template('joblist.html')
    context = {'job_list' : job_list}

    for job in job_list:
        job.city_name = Cities[job.job_city][1]
        job.type_name = JobTypes[job.job_type][1]

    #return HttpResponse(template.render(context))
    return render(requset,'joblist.html',context)

def detail(request,job_id):
    try:
        job = Job.objects.get(pk=job_id)
        job.city_name = Cities[job.job_city][1]
    except Job.DoesNotExist:
        raise Http404("Job does not exist")

    return render(request,'job.html',{'job':job})

from django.views.generic.detail import DetailView
# 复用DetailView
class ResumeDetailView(DetailView):
    """   简历详情页    """
    model = Resume
    template_name = 'resume_detail.html'


# Mixin使得可以继承多个父类
class ResumeCreateView(LoginRequiredMixin, CreateView):
    template_name = 'resume_form.html'
    success_url = '/joblist/'
    model= Resume
    fields = ["username", "city","phone",
              "email", "apply_position","gender",
              "bachelor_school", "master_school","major","degree","attachment",
              "candidate_introduction", "work_experience","project_experience"]

    def post(self, request, *args, **kwargs):
        form = ResumeForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            if len(request.FILES) == 0:
                pass
            else:
                uploaded_file = request.FILES['attachment']
                file_name = uploaded_file.name
                print(file_name)
                # 创建ObsClient实例
                obsClient = ObsClient(
                    access_key_id=ACCESS_KEY_ID,  # 刚刚下载csv文件里面的Access Key Id
                    secret_access_key=SECRET_ACCESS_KEY,  # 刚刚下载csv文件里面的Secret Access Key
                    server='https://' + ENDPOINT  # 这里的访问域名就是我们在桶的基本信息那里记下的东西
                )
                resp = obsClient.putFile(BUCKET_NAME, "media/" +file_name, file_path='./media/file/'+file_name)
                #print('requestId:', resp.requestId)
                """
                if resp.status < 300:
                    # 输出请求Id
                    
                else:
                    # 输出错误码
                    print('errorCode:', resp.errorCode)
                    # 输出错误信息
                    print('errorMessage:', resp.errorMessage)
                """
                # 关闭obsClient
                obsClient.close()
            return HttpResponseRedirect(self.success_url)
        return render(request,self.template_name,{'form':form})

    #从URL请求参数带入默认值
    def get_initial(self):
        initial = {}
        for x in self.request.GET:
            initial[x] = self.request.GET[x]
        return initial

    #简历跟当前用户关联
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.applicant = self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

